package com.ruoyi.web.controller.pdd;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pdd.pop.sdk.common.util.JsonUtil;
import com.pdd.pop.sdk.http.PopAccessTokenClient;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.file.request.PddGoodsImgUploadRequest;
import com.pdd.pop.sdk.http.api.file.response.PddGoodsImgUploadResponse;
import com.pdd.pop.sdk.http.api.pop.request.*;
import com.pdd.pop.sdk.http.api.pop.response.*;
import com.pdd.pop.sdk.http.token.AccessTokenResponse;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.config.webSocket.WebSocketServer;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.PddGoodsDetalVo;
import com.ruoyi.system.domain.vo.PddPropert;
import com.ruoyi.system.domain.vo.Pddgg;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsAddRequest.OverseaGoods;
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsAddRequest.SkuListItem;
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsAddRequest.SkuListItemOverseaSku;
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsAddRequest.SkuListItemSkuPropertiesItem;
import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;
import static com.ruoyi.common.utils.SecurityUtils.getUserId;

@RestController
@RequestMapping("/pdd")
public class TlPddController {
    @Autowired
    private ITlPddTokenService iTlPddTokenService;
    @Autowired
    private ITlPddGoodsService iTlPddGoodsService;
    @Autowired
    private ITlPddGoodsSkuService iTlPddGoodsSkuService;
    @Autowired
    private ITlPddGoodsSpecService iTlPddGoodsSpecService;
    @Autowired
    private ITlPddMallService iTlPddMallService;
    @Autowired
    private ITlPddMallTemplateService iTlPddMallTemplateService;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private TokenService tokenService;
    @Value("${ruoyi.clientId}")
    private String clientId;
    @Value("${ruoyi.clientSecret}")
    private String clientSecret;
    @Value("${ruoyi.dyAppid}")
    private String  dyAppid;
    @Value("${ruoyi.dySecretKey}")
    private String  dySecretKey;

    @GetMapping("/pddCallback")
    public AjaxResult pddCallback(@RequestParam("code") String code) throws Exception {
        System.out.println("code-----------------------------" + code);
        System.out.println("拼多多回调-------------------------");
        Long userId = null;
        //获取token
        PopAccessTokenClient client = new PopAccessTokenClient(
                clientId,
                clientSecret);
        AccessTokenResponse accessTokenResponse = client.generate(code);
        //获取店铺信息
        PopClient popclient = new PopHttpClient(clientId, clientSecret);
        PddMallInfoGetRequest request = new PddMallInfoGetRequest();
        PddMallInfoGetResponse response = popclient.syncInvoke(request, accessTokenResponse.getAccessToken());
        String res = JsonUtil.transferToJson(response);
        //判断店铺id是否已经有用户账号了
        SysUser sysUser = iSysUserService.selectUserById(Long.parseLong(accessTokenResponse.getOwnerId()));
        if(sysUser!=null){
            userId = sysUser.getUserId();
        }else {
            // 如果需要考虑时间，可以使用 LocalDateTime
            Date currentDate = new Date();
            // 创建 Calendar 对象并设置为当前时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(currentDate);
            // 往后推一个月
            calendar.add(Calendar.MONTH, 1);
            // 获取推后一个月后的时间
            Date nextMonth = calendar.getTime();
             sysUser = new SysUser();
             sysUser.setUserId(Long.parseLong(accessTokenResponse.getOwnerId()));//将店铺id设置成用户id
             sysUser.setIsyx("0");
             sysUser.setExTime(nextMonth);
             sysUser.setPassword(SecurityUtils.encryptPassword("doupinmofa111"));
            Long[] rIds = new Long[1];
            rIds[0] = 100L;
            //分配普通用户权限
            iSysUserService.insertUserAuth(sysUser.getUserId(),rIds);
            sysUser.setUserName(response.getMallInfoGetResponse().getMallName());
            sysUser.setAvatar(response.getMallInfoGetResponse().getLogo());
            sysUser.setNickName(response.getMallInfoGetResponse().getMallName());
            sysUser.setCreateTime(new Date());
            iSysUserService.insertUser(sysUser);
        }
        TlPddToken tlPddToken = iTlPddTokenService.selectTlPddTokenByUserIdAndoWnerId(accessTokenResponse.getOwnerId());
        //计算过期时间
        Calendar calendar = Calendar.getInstance();
        Date currentDate = calendar.getTime();
        calendar.setTime(currentDate);
        calendar.add(Calendar.MILLISECOND, accessTokenResponse.getExpiresIn());
        Date newDate = calendar.getTime();

        if (tlPddToken != null) {
            tlPddToken.setCode(code);
            tlPddToken.setAccessToken(accessTokenResponse.getAccessToken());
            tlPddToken.setExpiresIn(Long.parseLong(accessTokenResponse.getExpiresIn().toString()));
            tlPddToken.setExTime(newDate);
            tlPddToken.setRefreshToken(accessTokenResponse.getRefreshToken());
            tlPddToken.setOwnerId(accessTokenResponse.getOwnerId());
            tlPddToken.setOwnerName(accessTokenResponse.getOwnerName());
            iTlPddTokenService.updateTlPddToken(tlPddToken);
        } else {
            tlPddToken = new TlPddToken();
            tlPddToken.setCode(code);
            tlPddToken.setUserId(userId);
            tlPddToken.setAccessToken(accessTokenResponse.getAccessToken());
            tlPddToken.setExpiresIn(Long.parseLong(accessTokenResponse.getExpiresIn().toString()));
            tlPddToken.setRefreshToken(accessTokenResponse.getRefreshToken());
            tlPddToken.setOwnerId(accessTokenResponse.getOwnerId());
            tlPddToken.setOwnerName(accessTokenResponse.getOwnerName());
            tlPddToken.setExTime(newDate);
            iTlPddTokenService.insertTlPddToken(tlPddToken);
        }
        //保存店铺信息
        JSONObject jsonObject =  JSONObject.parseObject(res);
        JSONObject infoResponse = jsonObject.getJSONObject("mall_info_get_response");
        TlPddMall mall_id = iTlPddMallService.selectTlPddMallByMallId(infoResponse.getLong("mall_id"));
        if(mall_id==null){
            mall_id = new TlPddMall();
        }
        mall_id.setUserId(userId);
        mall_id.setLogo(infoResponse.getString("logo"));
        mall_id.setMallCharacter(infoResponse.getLong("mall_character"));
        mall_id.setMallName(infoResponse.getString("mall_name"));
        mall_id.setMerchantType(infoResponse.getLong("merchant_type"));
        mall_id.setMallDesc(infoResponse.getString("mall_desc"));
        if(mall_id.getId()==null){
            iTlPddMallService.insertTlPddMall(mall_id);
        }else {
            iTlPddMallService.updateTlPddMall(mall_id);
        }

        //同步店铺运费模板信息
        PddGoodsLogisticsTemplateGetRequest templateRequest = new PddGoodsLogisticsTemplateGetRequest();
        templateRequest.setPage(1);
        templateRequest.setPageSize(50);
        templateRequest.setGoodsStatus(0);
        PddGoodsLogisticsTemplateGetResponse templateResponse = popclient.syncInvoke(templateRequest, tlPddToken.getAccessToken());
        //清空当前登录用户当前店铺的模板信息，重新添加
        iTlPddMallTemplateService.deleteTlPddMallTemplateByUserIdAndMallId(userId,mall_id.getMallId());
        //重新添加模板信息
        List<PddGoodsLogisticsTemplateGetResponse.GoodsLogisticsTemplateGetResponseLogisticsTemplateListItem> logisticsTemplateList = templateResponse.getGoodsLogisticsTemplateGetResponse().getLogisticsTemplateList();
        if(logisticsTemplateList!=null && logisticsTemplateList.size()>0){
            for (PddGoodsLogisticsTemplateGetResponse.GoodsLogisticsTemplateGetResponseLogisticsTemplateListItem item:logisticsTemplateList) {
                TlPddMallTemplate tlPddMallTemplate = new TlPddMallTemplate();
                tlPddMallTemplate.setCostType(Long.parseLong(item.getCostType().toString()));
                tlPddMallTemplate.setLastUpdatedTime(new Date(item.getLastUpdatedTime()*1000));
                tlPddMallTemplate.setMallName(mall_id.getMallName());
                tlPddMallTemplate.setTemplateId(item.getTemplateId());
                tlPddMallTemplate.setTemplateName(item.getTemplateName());
                tlPddMallTemplate.setUserId(userId);
                tlPddMallTemplate.setMallId(mall_id.getMallId());
                iTlPddMallTemplateService.insertTlPddMallTemplate(tlPddMallTemplate);
            }
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(sysUser);
        loginUser.setUserId(sysUser.getUserId());
        loginUser.setDeptId(sysUser.getDeptId());
        loginUser.setIpaddr(IpUtils.getIpAddr());
        loginUser.setLoginTime(DateUtils.getNowDate().getTime());
        String token = tokenService.createToken(loginUser);
        Map<String, String> headers = new HashMap<>();
        headers.put("token", token);
        return AjaxResult.success(headers);
    }

    /**
     * 同步拼多多店铺商品
     *
     * @return
     */

//    @GetMapping("/pddSyncPddData")
//    public AjaxResult syncPddData() throws Exception {
//        Long userId = getLoginUser().getUserId();
//        //根据当前系统用户查询名下店铺然后循环遍历
////        List<TlPddToken> tlPddToken1 = iTlPddTokenService.selectTlPddTokenById(userId);
//
//        TlPddToken tlPddToken = iTlPddTokenService.selectTlPddTokenByUserIdAndoWnerId(userId, "734341652");
//        PopClient client = new PopHttpClient(clientId, clientSecret);
//        PddGoodsListGetRequest request = new PddGoodsListGetRequest();
////        request.setCostTemplateId(1L);
////        request.setCreatedAtEnd(1654099200L);
////        request.setCreatedAtFrom(1654012800L);
////        request.setGoodsName("str");
////        request.setIsOnsale(1);
////        request.setOuterGoodsId("1");
////        request.setOuterId("str");
//
//
//        //设置上架商品
//        //request.setIsOnsale(1);
//        //循环的次数
//        int count = 0;
//        //每次循环的总条数
//        int num = 0;
//        String s;
//        //开始时间结束时间
//        long endtime = new Date().getTime() / 1000;
//        long fromtime = endtime - 21600;
//        //商品的总条数
//        request.setPage(1);
//        request.setPageSize(100);
//        PddGoodsListGetResponse response = client.syncInvoke(request, tlPddToken.getAccessToken());
//        s = JsonUtil.transferToJson(response);
//        System.out.println("商品总数查询"+s);
//        JSONObject jsonObjects = JSONObject.parseObject(s);
//        String datas = jsonObjects.getString("goods_list_get_response");
//        JSONObject parses = JSONObject.parse(datas);
//        int total_count = Integer.parseInt(parses.getString("total_count"));
//
//        do {
//            if (num <= 100) {
////                if (endtime != new Date().getTime() / 1000) {
////                    endtime = fromtime;
////                    fromtime = fromtime - 21600;
////                }
////                //开始时间当前时间减去12个小时的时间戳
////                request.setCreatedAtFrom(fromtime);
////                //结束时间
////                request.setCreatedAtEnd(endtime);
//                request.setPage(1);
//                request.setPageSize(100);
//                PddGoodsListGetResponse responses = client.syncInvoke(request, tlPddToken.getAccessToken());
//                s = JsonUtil.transferToJson(responses);
//                System.out.println("第一页查询"+s);
//
//                //将json数据格式转换保存到对象内
//                JSONObject jsonObject = JSONObject.parseObject(s);
//                String data = jsonObject.getString("goods_list_get_response");
//                if (data==null){
//                    Thread.sleep(2000);
//                    continue;
//                }
//                JSONObject parse = JSONObject.parse(data);
//                num = Integer.parseInt(parse.getString("total_count"));
//                String data1 = parse.getString("goods_list");
//                List<TlPddGoods> list=new ArrayList<>();
//                List<TlPddGoodsSku> skulist=new ArrayList<>();
//                List<TlPddGoodsSpec> speclist=new ArrayList<>();
//                if (data1 != null && !data1.equals("")) {
//                    JSONArray parse1 = JSONArray.parse(data1);
//                    for (int i = 0; i < parse1.size(); i++) {
//                        //商品列表同步
//                        Object o = parse1.get(i);
//                        TlPddGoods tlPddGoods = JSONObject.parseObject(o.toString(), TlPddGoods.class);
//                        tlPddGoods.setOwnerId(734341652L);
//                        tlPddGoods.setOwnerName("pdd73434165210");
//                        tlPddGoods.setUserId(userId);
//                        list.add(tlPddGoods);
//                        //记录商品的个数
//                        count++;
//                        //商品sku列表
//                        String data2 = parse1.getJSONObject(i).getString("sku_list");
//                        JSONArray parse2 = JSONArray.parse(data2);
//                        for (int i1 = 0; i1 < parse2.size(); i1++) {
//                            Object o1 = parse2.get(i1);
//                            TlPddGoodsSku tlPddGoodsSku = JSONObject.parseObject(o1.toString(), TlPddGoodsSku.class);
//                            tlPddGoodsSku.setGoodId(tlPddGoods.getGoodsId());
//                            skulist.add(tlPddGoodsSku);
//                            //商品规格列表
//                            String data3 = parse2.getJSONObject(i1).getString("spec_details");
//                            if (data3 != null && !data3.equals("")) {
//                                JSONArray parse3 = JSONArray.parse(data3);
//                                for (int i2 = 0; i2 < parse3.size(); i2++) {
//                                    Object o2 = parse3.get(i2);
//                                    TlPddGoodsSpec tlPddGoodsSpec = JSONObject.parseObject(o2.toString(), TlPddGoodsSpec.class);
//                                    tlPddGoodsSpec.setGoodId(tlPddGoods.getGoodsId());
//                                    speclist.add(tlPddGoodsSpec);
//                                }
//                            }
//                        }
//                    }
//                    if (!list.isEmpty()) {
//                        iTlPddGoodsService.insertTlPddGoodsAll(list);
//                    }
//                    if (!skulist.isEmpty()){
//                        iTlPddGoodsSkuService.insertTlPddGoodsSkuAll(skulist);
//                    }
//                    if (!speclist.isEmpty()){
//                        iTlPddGoodsSpecService.insertTlPddGoodsSpecAll(speclist);
//                    }
//                }
//            } else {
//                num = (int) Math.ceil(num / 100);
//                for (int y = 2; y <= num; y++) {
//                    //时间区间不变
//                    request.setCreatedAtFrom(fromtime);
//                    request.setCreatedAtEnd(endtime);
//                    request.setPage(y);
//                    request.setPageSize(100);
//                    PddGoodsListGetResponse responses = client.syncInvoke(request, tlPddToken.getAccessToken());
//                    s = JsonUtil.transferToJson(responses);
//                    System.out.println("其他页查询"+s);
//
//                    //将json数据格式转换保存到对象内
//                    JSONObject jsonObject = JSONObject.parseObject(s);
//                    if (jsonObject.getString("goods_list_get_response")==null){
//                        Thread.sleep(2000);
//                        responses = client.syncInvoke(request, tlPddToken.getAccessToken());
//                        s = JsonUtil.transferToJson(responses);
//                        jsonObject = JSONObject.parseObject(s);
//                    }
//                    String data = jsonObject.getString("goods_list_get_response");
//                    JSONObject parse = JSONObject.parse(data);
//                    String data1 = parse.getString("goods_list");
//                    List<TlPddGoods> list=new ArrayList<>();
//                    List<TlPddGoodsSku> skulist=new ArrayList<>();
//                    List<TlPddGoodsSpec> speclist=new ArrayList<>();
//                    if (data1 != null && !data1.equals("")) {
//                        JSONArray parse1 = JSONArray.parse(data1);
//                        for (int i = 0; i < parse1.size(); i++) {
//                            //商品列表同步
//                            Object o = parse1.get(i);
//                            TlPddGoods tlPddGoods = JSONObject.parseObject(o.toString(), TlPddGoods.class);
//                            tlPddGoods.setOwnerId(734341652L);
//                            tlPddGoods.setOwnerName("pdd73434165210");
//                            tlPddGoods.setUserId(userId);
//                            list.add(tlPddGoods);
//                            //记录商品的个数
//                            count++;
//                            //商品sku列表
//                            String data2 = parse1.getJSONObject(i).getString("sku_list");
//                            JSONArray parse2 = JSONArray.parse(data2);
//                            for (int i1 = 0; i1 < parse2.size(); i1++) {
//                                Object o1 = parse2.get(i1);
//                                TlPddGoodsSku tlPddGoodsSku = JSONObject.parseObject(o1.toString(), TlPddGoodsSku.class);
//                                tlPddGoodsSku.setGoodId(tlPddGoods.getGoodsId());
//                                skulist.add(tlPddGoodsSku);
//                                //商品规格列表
//                                String data3 = parse2.getJSONObject(i1).getString("spec_details");
//                                if (data3 != null && !data3.equals("")) {
//                                    JSONArray parse3 = JSONArray.parse(data3);
//                                    for (int i2 = 0; i2 < parse3.size(); i2++) {
//                                        Object o2 = parse3.get(i2);
//                                        TlPddGoodsSpec tlPddGoodsSpec = JSONObject.parseObject(o2.toString(), TlPddGoodsSpec.class);
//                                        tlPddGoodsSpec.setGoodId(tlPddGoods.getGoodsId());
//                                        speclist.add(tlPddGoodsSpec);
//                                    }
//                                }
//                            }
//                        }
//                        if (!list.isEmpty()) {
//                            iTlPddGoodsService.insertTlPddGoodsAll(list);
//                        }
//                        if (!skulist.isEmpty()){
//                            iTlPddGoodsSkuService.insertTlPddGoodsSkuAll(skulist);
//                        }
//                        if (!speclist.isEmpty()){
//                            iTlPddGoodsSpecService.insertTlPddGoodsSpecAll(speclist);
//                        }
//                    }
//                }
//            }
//        } while (count < total_count);
////        System.out.println(s);
//        return AjaxResult.success(s);
//    }


    @GetMapping("/pddSyncPddData/{ownerId}")
    public AjaxResult syncPddData(@PathVariable("ownerId") String ownerId) throws Exception {
        Long userId = getLoginUser().getUserId();

        //删除现有数据
        iTlPddGoodsService.deleteTlPddGoodsByUserIdAndOwnerId(userId,Long.valueOf(ownerId));
        iTlPddGoodsSkuService.deleteTlPddGoodsSkuByUserIdAndOwnerId(userId,Long.valueOf(ownerId));
        iTlPddGoodsSpecService.deleteTlPddGoodsSpecByUserIdAndOwnerId(userId,Long.valueOf(ownerId));

        TlPddToken tlPddToken = iTlPddTokenService.selectTlPddTokenByUserIdAndoWnerId(ownerId);
        PopClient client = new PopHttpClient(clientId, clientSecret);
        PddGoodsListGetRequest request = new PddGoodsListGetRequest();
//        request.setCostTemplateId(1L);
//        request.setCreatedAtEnd(1654099200L);
//        request.setCreatedAtFrom(1654012800L);
//        request.setGoodsName("str");
        request.setIsOnsale(1);
//        request.setOuterGoodsId("1");
//        request.setOuterId("str");

        String s;
        //记录个数
        int count = 0;
        //开始时间
        Long fromtime = 0L;
        Long endTime = 0L;
        //请求页数
        Integer page = 0;

        //商品的总条数
        PddGoodsListGetResponse response = client.syncInvoke(request, tlPddToken.getAccessToken());
        s = JsonUtil.transferToJson(response);
        JSONObject jsonObjects = JSONObject.parseObject(s);
        if(jsonObjects.getString("error_response") != null) {
            return AjaxResult.error("授权失效，请先进行授权");
        }
        String datas = jsonObjects.getString("goods_list_get_response");
        JSONObject parses = JSONObject.parse(datas);
        //商品总条数
        Integer total_count = Integer.parseInt(parses.getString("total_count"));

        //使用webSocket把总数发送到前台
        JSONObject res = new JSONObject();
        res.put("action","total");
        res.put("total",total_count);
        webSocketServer.sendInfo(res.toJSONString(),userId.toString());

        //当前查询条件的商品总条数
        Integer total = 0;

        Map<Long,Integer> goodsId = new HashMap<>();

        while (count < total_count) {
            //请求接口，判断本次循环页数
            if(fromtime != 0L && endTime != 0L) {
                request.setCreatedAtFrom(fromtime);
                request.setCreatedAtEnd(endTime);
            }
            response = client.syncInvoke(request, tlPddToken.getAccessToken());
            s = JsonUtil.transferToJson(response);
            jsonObjects = JSONObject.parseObject(s);
            datas = jsonObjects.getString("goods_list_get_response");
            parses = JSONObject.parse(datas);
            total = Integer.parseInt(parses.getString("total_count"));

            //判断商品总数是否大于1万条。确定分页数量
            page = total > 10000 ? 100 : (int)Math.ceil(total/100.0);

            for (int x = 1; x <= page; x++) {
                if (fromtime != 0L && endTime != 0L){
                    request.setCreatedAtFrom(fromtime);
                    request.setCreatedAtEnd(endTime);
                }
                request.setPage(x);
                request.setPageSize(100);
                response = client.syncInvoke(request, tlPddToken.getAccessToken());
                s = JsonUtil.transferToJson(response);

                JSONObject jsonObject = JSONObject.parseObject(s);
                String data = jsonObject.getString("goods_list_get_response");
                JSONObject parse = JSONObject.parse(data);
                //重新复制条件商品总条数
                total = Integer.parseInt(parse.getString("total_count"));
                String data1 = parse.getString("goods_list");
                List<TlPddGoods> list = new ArrayList<>();
                List<TlPddGoodsSku> skulist = new ArrayList<>();
                List<TlPddGoodsSpec> speclist = new ArrayList<>();

                if (data1 != null && !data1.equals("")) {
                    JSONArray parse1 = JSONArray.parse(data1);
                    if(parse1.size() == 0) {
                        //如果请求结果条数是0。就重新设置时间条件。并跳出本次循环
                        fromtime = endTime;
                        endTime = fromtime + 604800L;
                        continue;
                    }
                    for (int i = 0; i < parse1.size(); i++) {
                        //商品列表同步
                        Object o = parse1.get(i);
                        TlPddGoods tlPddGoods = JSONObject.parseObject(o.toString(), TlPddGoods.class);
                        tlPddGoods.setOwnerId(Long.valueOf(tlPddToken.getOwnerId()));
                        tlPddGoods.setOwnerName(tlPddToken.getOwnerName());
                        tlPddGoods.setUserId(userId);
                        //当查询到当前搜索条件最后一条记录时。把最后一条记录的创建时间设置为下次查询的开始时间
                        if (x == page && i == parse1.size() - 1){
                            if(fromtime != Long.parseLong(tlPddGoods.getCreatedAt())) {
                                fromtime = Long.parseLong(tlPddGoods.getCreatedAt());
                                endTime = fromtime + 604800L;
                            } else {
                                fromtime = endTime;
                                endTime = fromtime + 604800L;
                            }
                        }
                        //在该次查询第一页。判断是否已经读取过该数据
                        if(x == 1) {
                            Integer isSave = goodsId.get(tlPddGoods.getGoodsId());
                            if(isSave != null) {
                                continue;
                            }
                        }
                        //在该次查询最后一页。记录商品id
                        if(x == page) {
                            goodsId.put(tlPddGoods.getGoodsId(),1);
                        }
                        list.add(tlPddGoods);
                        //记录一共存了多少条数据
                        count++;
                        //把已经同步的个数发向前台
                        res = new JSONObject();
                        res.put("action","tongbu");
                        res.put("count",count);
                        webSocketServer.sendInfo(res.toJSONString(),userId.toString());

                        //商品sku列表
                        String data2 = parse1.getJSONObject(i).getString("sku_list");
                        JSONArray parse2 = JSONArray.parse(data2);
                        for (int i1 = 0; i1 < parse2.size(); i1++) {
                            Object o1 = parse2.get(i1);
                            TlPddGoodsSku tlPddGoodsSku = JSONObject.parseObject(o1.toString(), TlPddGoodsSku.class);
                            tlPddGoodsSku.setGoodId(tlPddGoods.getGoodsId());
                            tlPddGoodsSku.setUserId(tlPddGoods.getUserId());
                            tlPddGoodsSku.setOwnerId(tlPddGoods.getOwnerId());
                            skulist.add(tlPddGoodsSku);
                            //商品规格列表
                            String data3 = parse2.getJSONObject(i1).getString("spec_details");
                            if (data3 != null && !data3.equals("")) {
                                JSONArray parse3 = JSONArray.parse(data3);
                                for (int i2 = 0; i2 < parse3.size(); i2++) {
                                    Object o2 = parse3.get(i2);
                                    TlPddGoodsSpec tlPddGoodsSpec = JSONObject.parseObject(o2.toString(), TlPddGoodsSpec.class);
                                    tlPddGoodsSpec.setGoodId(tlPddGoods.getGoodsId());
                                    tlPddGoodsSpec.setUserId(tlPddGoods.getUserId());
                                    tlPddGoodsSpec.setOwnerId(tlPddGoods.getOwnerId());
                                    speclist.add(tlPddGoodsSpec);
                                }
                            }
                        }
                    }
                    if (!list.isEmpty()) {
                        iTlPddGoodsService.insertTlPddGoodsAll(list);
                    }
                    if (!skulist.isEmpty()) {
                        iTlPddGoodsSkuService.insertTlPddGoodsSkuAll(skulist);
                    }
                    if (!speclist.isEmpty()) {
                        iTlPddGoodsSpecService.insertTlPddGoodsSpecAll(speclist);
                    }
                    Thread.sleep(500);
                    System.out.println("添加个数/总个数："+count+"/"+total_count);

                }
            }
            Thread.sleep(2000);
        }
        return AjaxResult.success(s);
    }
    @PostMapping("/pddGoodsUpload")
    public AjaxResult pddGoodsUpload(MultipartFile file,String sensitiveWords,Long mallId) throws Exception {
        System.out.println(sensitiveWords);
        if (file.isEmpty()) {
            return AjaxResult.error("上传的文件为空");
        }
        List<TlDyDoodsDetail> tlDyDoodsDetails = new ArrayList<>();
        TlPddToken tlPddToken = iTlPddTokenService.selectTlPddTokenByUserIdAndoWnerId(mallId.toString());
        //对接拼多多上传接口
        String accessToken = tlPddToken.getAccessToken();
        try {
            InputStream inputStream = file.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                if(line!=null && !line.equals("")){
                    int i = line.lastIndexOf("=");
                    String dyId = line.substring(i+1);
                    String detail = HttpUtils.sendPost("https://www.zcxq.com/v1/leya/share/goods/detail/", "product_id=" + dyId);
                    JSONObject detailjsonObject =  JSONObject.parseObject(detail);
                    String detailcode = detailjsonObject.getString("code");
                    if(!detailcode.equals("200")){
                        continue;
                    }
                    //解析详情
                    String detailData = detailjsonObject.getString("data");
                    TlDyDoodsDetail tlDyDoodsDetail = JSONObject.parseObject(detailData, TlDyDoodsDetail.class);
                    PopClient client = new PopHttpClient(clientId, clientSecret);
                    PddGoodsOuterCatMappingGetRequest catRequest = new PddGoodsOuterCatMappingGetRequest();
                    catRequest.setOuterCatId(tlDyDoodsDetail.getCategoryId());
                    catRequest.setOuterCatName(tlDyDoodsDetail.getCategoryName());
                    catRequest.setOuterGoodsName(tlDyDoodsDetail.getTitle());
                    PddGoodsOuterCatMappingGetResponse catResponse = client.syncInvoke(catRequest, accessToken);
                    //设置类目
                    if(catResponse.getOuterCatMappingGetResponse()==null){
                        throw new RuntimeException("店铺授权过期，请重新授权");
                    }
                    tlDyDoodsDetail.setCategoryId(catResponse.getOuterCatMappingGetResponse().getCatId4());
                    tlDyDoodsDetail.setCategoryId3(catResponse.getOuterCatMappingGetResponse().getCatId3());
                    tlDyDoodsDetails.add(tlDyDoodsDetail);
                }
            }
            reader.close();
            List<TlDyDoodsDetail> distinctList = tlDyDoodsDetails.stream()
                    .collect(Collectors.toMap(TlDyDoodsDetail::getProductId, d -> d, (oldValue, newValue) -> oldValue))
                    .values().stream()
                    .collect(Collectors.toList());
            return AjaxResult.success(distinctList);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("读取文件内容失败");
        }
    }

    /**
     * 上传抖音接口
     * @return
     */
    @PostMapping("/uploadGoods")
    public AjaxResult uploadGoods(@RequestBody PddGoodsDetalVo pddGoodsDetalVo) throws Exception {
        TlPddToken tlPddToken = iTlPddTokenService.selectTlPddTokenByUserIdAndoWnerId(pddGoodsDetalVo.getMallId().toString());
        //对接拼多多上传接口
        String accessToken = tlPddToken.getAccessToken();
        TlPddMall tlPddMall = iTlPddMallService.selectTlPddMallByMallId(pddGoodsDetalVo.getMallId());
        int num = 1;
        for (TlDyDoodsDetail tlDyDoodsDetail:pddGoodsDetalVo.getTlDyDoodsDetails()) {
            List<Pddgg> bt = tlDyDoodsDetail.getPddggs();
            if(bt==null || bt.size()==0){
                Map<String,Object> stringObjectMap = new HashMap<>();
                stringObjectMap.put("data",tlDyDoodsDetail);
                stringObjectMap.put("msg","未设置必填项");
                stringObjectMap.put("errorType","1");
                stringObjectMap.put("cuNum",num);
                stringObjectMap.put("sumNum",pddGoodsDetalVo.getTlDyDoodsDetails().size());
                webSocketServer.sendInfo(new JSONObject(stringObjectMap).toJSONString(),getUserId().toString());
            }
            //对接拼多多上传
            PopClient client = new PopHttpClient(clientId, clientSecret);
            PddGoodsAddRequest request = new PddGoodsAddRequest();

            //商品轮播图、详情图
            List<String> carouselGallery = new ArrayList<String>();
            JSONArray jsonArray = new JSONArray(tlDyDoodsDetail.getImgs());
            for (int i = 0; i < jsonArray.size(); i++) {
//                carouselGallery.add(jsonArray.getString(i));
                carouselGallery.add("https://img.pddpic.com/open-gw/2023-11-25/7a6d9fb0-a603-47a1-9e6f-ca647e0fdb58.jpeg");
            }
            request.setCarouselGallery(carouselGallery);

            PddGoodsOuterCatMappingGetRequest catRequest = new PddGoodsOuterCatMappingGetRequest();
            catRequest.setOuterCatId(tlDyDoodsDetail.getCategoryId());
            catRequest.setOuterCatName(tlDyDoodsDetail.getCategoryName());
            catRequest.setOuterGoodsName(tlDyDoodsDetail.getTitle());
            PddGoodsOuterCatMappingGetResponse catResponse = client.syncInvoke(catRequest, accessToken);
            //设置类目
            request.setCatId(catResponse.getOuterCatMappingGetResponse().getCatId4());
            //设置运费模板
            request.setCostTemplateId(tlPddMall.getYunfeimoban());
            //地区/国家ID
            request.setCountryId(0);
            //商品详情图
            List<String> detailGallery = new ArrayList<String>();
            JSONArray detailImgs = new JSONArray(tlDyDoodsDetail.getDetail());
            for (int i = 0; i < detailImgs.size(); i++) {
//                detailGallery.add(detailImgs.getString(i));
                detailGallery.add("https://img.pddpic.com/open-gw/2023-11-25/7a6d9fb0-a603-47a1-9e6f-ca647e0fdb58.jpeg");
            }
            request.setDetailGallery(detailGallery);
            //商品描述
            request.setGoodsDesc(tlDyDoodsDetail.getTitle());
            //商品标题
            request.setGoodsName(tlDyDoodsDetail.getTitle());
            //国内普通商品
            request.setGoodsType(1);
            // 设置-是否假一赔十
            if(tlPddMall.getJiayipeishi()==null){
                Map<String,Object> stringObjectMap = new HashMap<>();
                stringObjectMap.put("data",tlDyDoodsDetail);
                stringObjectMap.put("msg","店铺未设置是否假一赔十");
                stringObjectMap.put("errorType","1");
                stringObjectMap.put("cuNum",num);
                stringObjectMap.put("sumNum",pddGoodsDetalVo.getTlDyDoodsDetails().size());
                webSocketServer.sendInfo(new JSONObject(stringObjectMap).toJSONString(),getUserId().toString());
                num++;
                continue;
            }
            request.setIsFolt(1 == tlPddMall.getJiayipeishi());
            //是否预售
            request.setIsPreSale(false);
            if(tlPddMall.getQitian()==null){
                Map<String,Object> stringObjectMap = new HashMap<>();
                stringObjectMap.put("data",tlDyDoodsDetail);
                stringObjectMap.put("msg","店铺未设置是否7天无理由退换货");
                stringObjectMap.put("errorType","1");
                stringObjectMap.put("cuNum",num);
                stringObjectMap.put("sumNum",pddGoodsDetalVo.getTlDyDoodsDetails().size());
                webSocketServer.sendInfo(new JSONObject(stringObjectMap).toJSONString(),getUserId().toString());
                num++;
                continue;
            }
            // 设置是否7天无理由退换货，true-支持，false-不支持
            request.setIsRefundable(1 == tlPddMall.getQitian());
            // 设置参考价格，单位为分
            request.setMaiJiaZiTi(tlDyDoodsDetail.getPrice().multiply(new BigDecimal("100")).toString());

            request.setMarketPrice((tlDyDoodsDetail.getPrice().multiply(new BigDecimal(100))).longValue());
            request.setOutGoodsId(tlDyDoodsDetail.getProductId().toString());
            request.setOutSourceGoodsId(tlDyDoodsDetail.getProductId().toString());
            request.setSecondHand(false);
            //设置承诺发货时间（秒）
            request.setShipmentLimitSecond(86400L);

            List<SkuListItem> skuList = new ArrayList<SkuListItem>();
            List<Pddgg> pddggs = tlDyDoodsDetail.getPddggs();
            for (Pddgg pddgg:pddggs) {
                SkuListItem item2 = new SkuListItem();
                //上架状态
                item2.setIsOnsale(1);
                //限购数量
                item2.setLimitQuantity(999L);
                //拼团价
                item2.setMultiPrice(Long.parseLong(pddgg.getPdj()));
                //外部编号
                item2.setOutSkuSn(tlDyDoodsDetail.getProductId().toString());
                //外部id
                item2.setOutSourceSkuId(tlDyDoodsDetail.getProductId().toString());
                //单买价
                item2.setPrice(Long.parseLong(pddgg.getDmj()));
                //库存
                item2.setQuantity(Long.parseLong(pddgg.getKc()));
                List<PddPropert> sku_properties = tlDyDoodsDetail.getSku_properties();
                List<SkuListItemSkuPropertiesItem> skuProperties = new ArrayList<SkuListItemSkuPropertiesItem>();
                for (PddPropert pddPropert:sku_properties) {
                    SkuListItemSkuPropertiesItem item3 = new SkuListItemSkuPropertiesItem();
                    item3.setPunit(pddPropert.getPunit());
                    item3.setRefPid(pddPropert.getRef_pid());
                    item3.setValue(pddPropert.getValue());
                    item3.setVid(pddPropert.getVid());
                    skuProperties.add(item3);
                }

                item2.setSkuProperties(skuProperties);
                List<String> ggs = new ArrayList<>();
                PopClient ggclient = new PopHttpClient(clientId, clientSecret);

                PddGoodsSpecIdGetRequest ggrequest = new PddGoodsSpecIdGetRequest();
                ggrequest.setParentSpecId(tlDyDoodsDetail.getParentSpecId());
                ggrequest.setSpecName(pddgg.getValue());
                PddGoodsSpecIdGetResponse response = ggclient.syncInvoke(ggrequest, accessToken);
                ggs.add(response.getGoodsSpecIdGetResponse().getSpecId().toString());
                item2.setSpecIdList(ggs.toString());
                item2.setThumbUrl("https://img.pddpic.com/open-gw/2023-11-25/7a6d9fb0-a603-47a1-9e6f-ca647e0fdb58.jpeg");
                item2.setWeight(100L);
                skuList.add(item2);
            }
            request.setTwoPiecesDiscount(tlDyDoodsDetail.getManliangjian());
            request.setSkuList(skuList);
            PddGoodsAddResponse response = client.syncInvoke(request,accessToken);
            if(response.getGoodsAddResponse()==null){
                Map<String,Object> stringObjectMap = new HashMap<>();
                stringObjectMap.put("data",tlDyDoodsDetail);
                stringObjectMap.put("msg",response.getErrorResponse().getErrorMsg());
                stringObjectMap.put("errorType","1");
                stringObjectMap.put("cuNum",num);
                stringObjectMap.put("sumNum",pddGoodsDetalVo.getTlDyDoodsDetails().size());
                webSocketServer.sendInfo(new JSONObject(stringObjectMap).toJSONString(),getUserId().toString());
            }
            num++;
        }
        return null;
    }

    /**
     * 查询类目
     * @return
     */
    @GetMapping("/findCats/{id}")
    public AjaxResult findCats(@PathVariable("id") Long id) throws Exception {
        PopClient client = new PopHttpClient(clientId, clientSecret);
        PddGoodsCatsGetRequest request = new PddGoodsCatsGetRequest();
        request.setParentCatId(id);
        PddGoodsCatsGetResponse response = client.syncInvoke(request);
        List<PddGoodsCatsGetResponse.GoodsCatsGetResponseGoodsCatsListItem> goodsCatsList = response.getGoodsCatsGetResponse().getGoodsCatsList();
        return AjaxResult.success(goodsCatsList);
    }

    @GetMapping("/findRoleData/{cId}/{mallId}")
    public AjaxResult findRoleData(@PathVariable("cId") Long cid,@PathVariable("mallId") Long mallId) throws Exception {
        TlPddToken tlPddToken = iTlPddTokenService.selectTlPddTokenByUserIdAndoWnerId(mallId.toString());
        //对接拼多多上传接口
        String accessToken = tlPddToken.getAccessToken();
        PopClient client = new PopHttpClient(clientId, clientSecret);
        PddGoodsCatRuleGetRequest request = new PddGoodsCatRuleGetRequest();
        request.setCatId(cid);
        PddGoodsCatRuleGetResponse response = client.syncInvoke(request, accessToken);
        return AjaxResult.success(response);
    }

    @PostMapping("/findvalueSearch")
    public AjaxResult findvalueSearch(Long cid,Long mallId,String value,Long refPid) throws Exception {
        TlPddToken tlPddToken = iTlPddTokenService.selectTlPddTokenByUserIdAndoWnerId( mallId.toString());
        PopClient client = new PopHttpClient(clientId, clientSecret);
        PddGoodsTemplatePropertyValueSearchRequest request = new PddGoodsTemplatePropertyValueSearchRequest();
        request.setCatId(cid);
        request.setPageNum(0);
        request.setPageSize(100);
        request.setValue(value);
        request.setRefPid(refPid);
        PddGoodsTemplatePropertyValueSearchResponse response = client.syncInvoke(request, tlPddToken.getAccessToken());
        return AjaxResult.success(response);
    }
    @PostMapping("/specGet")
    public AjaxResult specGet(Long cid,Long mallId) throws Exception {
        PopClient client = new PopHttpClient(clientId, clientSecret);
        TlPddToken tlPddToken = iTlPddTokenService.selectTlPddTokenByUserIdAndoWnerId( mallId.toString());
        PddGoodsSpecGetRequest request = new PddGoodsSpecGetRequest();
        request.setCatId(cid);
        PddGoodsSpecGetResponse response = client.syncInvoke(request, tlPddToken.getAccessToken());
        return AjaxResult.success(response);
    }

    @PostMapping("/pddGoodsUploadslt")
    public AjaxResult pddGoodsUploadslt(MultipartFile file,Long mallId) throws Exception {
        String tempFilePath = FileUtils.saveMultipartFileToTempFile(file);
        TlPddToken tlPddToken = iTlPddTokenService.selectTlPddTokenByUserIdAndoWnerId( mallId.toString());
        PopClient client = new PopHttpClient(clientId, clientSecret);
        PddGoodsImgUploadRequest request = new PddGoodsImgUploadRequest();
        request.setFile(tempFilePath);
        PddGoodsImgUploadResponse response = client.syncInvoke(request, tlPddToken.getAccessToken());
        return AjaxResult.success(response);
    }


}
